-- UISkyCityWingman
-- Create by chendh
-- 僚机（副炮）选择界面

require "game/ui/form/hero/HeroUtil"

-- UISkyCityWingman继承自Layer
UISkyCityWingman = class("UISkyCityWingman", function()
    return cc.Layer:create();
end);

function UISkyCityWingman.create(skillType)
    return UISkyCityWingman.new(skillType);
end

-- 僚机格最大行数
local MIN_GRID_COLUMN = 4;
local MAX_GRID_ROW    = 6;
local ITEM_NAME       = "item";

-- 构造函数
function UISkyCityWingman:ctor(skillType)
    -- 初始化
    self:setName("UISkyCityWingman");
    local node = cc.CSLoader:createNode("layout/lictor/LictorChoose.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    self.CT = CT;
    local scroll_view = findChildByName(self.node, "CT/bg_1/scroll_view");
    self.scrollView = scroll_view;
    self.selectIndex = 1;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.skillType = skillType;
    self.shipList = NewAirShipM.getShipBySkillType(skillType);
    self.skillTypeName = getLocStr("airship_skill_type" .. skillType);

    -- 注册点击事件
    self:registerTouchEvent();

    self:initData();

    -- 初始化僚机格子
    self:initWingmanGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UISkyCityWingman 界面析构清理");
            EventMgr.removeAll("UISkyCityWingman");
        elseif ev == "enter" then

        end
    end);
end

-- 重绘
function UISkyCityWingman:redraw()
    -- 绘制标题
    local titleLabel = findChildByName(self.CT, "title/title_label");
    titleLabel:setString(getLocStr("wingman_title"));
    TextStyleM.setTitleStyle(titleLabel);

    -- 绘制副标题
    local titleExplainLabel = findChildByName(self.CT, "title/title_explain");
    titleExplainLabel:setString(string.format(getLocStr("wingman_subhead"), self.skillTypeName));
    TextStyleM.setSubheadStyle(titleExplainLabel);

    -- 绘制页面
    local itemCount = #self.data;
    local index = 0;

    if not self.data or itemCount == 0 then
        cclog("收集僚机信息失败。");
        self:clearAllGrid();
        return;
    end

    -- 找到第一个可派遣
    for i = 1, itemCount do
        local data = self.data[i];
        if data then
            local shipId = data["shipId"];
            -- 已经拥有该飞艇
            if NewAirShipM.hasOwnShip(shipId) then
                self.selectIndex = i;
                break;
            end
        end
    end

    for index = 1, itemCount do
        -- 获取僚机格
        local child = self.scrollView:getChildByName(ITEM_NAME .. index);
        if child == nil then
            break;
        end

        -- 设置选中效果
        local focusBg = child:getChildByName("focus");
        if self.selectIndex == index then
            focusBg:setVisible(true);
        else
            focusBg:setVisible(false);
        end

        -- 僚机格文本
        local str = "";
        -- 僚机格背景
        local bgImg = child:getChildByName("bg");
        local bgImgGray = child:getChildByName("gray_bg");
        -- 僚机icon
        local iconImage = child:getChildByName("icon");
        -- 僚机格星级
        local starImage = child:getChildByName("rank");
        -- "已链接"的tip
        local tipImage = child:getChildByName("tip");

           -- 系别图标
        local departImg = child:getChildByName("depart_img");

        -- 默认全部隐藏
        bgImg:setVisible(false);
        bgImgGray:setVisible(false);
        iconImage:setVisible(false);
        starImage:setVisible(false);
        tipImage:setVisible(false);
        departImg:setVisible(false);

        local data = self.data[index];
        if data then
            -- 有数据

            -- 设置僚机主炮图标
            local shipId = data["shipId"];
            local skillId = data["skillId"];
            local iconIndex = SkyShipSkillM.query(skillId, "icon")
            iconImage:loadTexture(getAirShipSkillIconPath(iconIndex));
            iconImage:setVisible(true);

            if NewAirShipM.hasOwnShip(shipId) then
                -- 玩家已获得该飞艇

                -- 正常显示图标、背景、星级
                iconImage:setOpacity(255);
                bgImg:setVisible(true);
                bgImg:loadTexture("images/ui/lictor/bg1.png");

                -- 设置星阶
                -- 星级控件
                starImage:setVisible(true);
                if data then
                    local tStar = createStarLayer(data.rank,"images/ui/symbol/star_little.png", "center", -0.7);
                    if tStar then
                        starImage:removeAllChildren();
                        starImage:addChild(tStar);
                    end
                end

            else
                -- 无法连接
                -- 虚化显示飞艇技能和背景
                iconImage:setOpacity(125.5);
                bgImg:setVisible(true);
                bgImg:loadTexture("images/ui/lictor/bg3.png");
            end
        end
    end

    self:refreshExplain();

    -- 设置选择按钮是否可用
    local btnSelect = findChildByName(self.node, "BT/choose_btn");
    btnSelect:setBright(false);
    btnSelect:setTouchEnabled(false);

    local data = self.data[self.selectIndex];
    if not data then
        return;
    end

    if self:canDispatch(data.shipId) then
        btnSelect:setBright(true);
        btnSelect:setTouchEnabled(true);
    end
end

-- 设置说明
function UISkyCityWingman:refreshExplain()
    local data = self.data[self.selectIndex];

    -- 先把标题和描述隐藏起来
    local captionLabel = findChildByName(self.CT, "bg_2/caption_label");
    captionLabel:setVisible(false);
    local Label = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    Label:setVisible(false);

    if not data then
        data = {};
        data.skillLevel = 0;
        return;
    end

    local shipId = data["shipId"];
    local skillId = data["skillId"];
    local skillLevel = data["skillLevel"] + 1;

    -- 将技能名设置为标题
    local skillName = SkyShipSkillM.query(skillId, "name");
    captionLabel:setVisible(true);
    TextStyleM.setTextStyle(captionLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);

    if not NewAirShipM.hasOwnShip(shipId) then
        -- 尚未获得飞艇，仅显示技能名称
        captionLabel:setString(skillName);
    else
        captionLabel:setString(skillName .. " Lv." .. skillLevel);
    end

    -- 技能描述
    local explainText = data["skillDesc"];
    local explainLabel = findChildByName(self.CT, "bg_2/explain_scroll/explain");
    explainLabel:setVisible(true);
    TextStyleM.setTextStyle(explainLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    local shipName = NewAirShipM.query(shipId, "name");
    if not NewAirShipM.hasOwnShip(shipId) then
        -- 未获得飞艇
        explainText = string.format(getLocStr("wingman_explain2"), shipName);
    else
        -- 已获得飞艇
        explainText = explainText .. "\n\n" .. string.format(getLocStr("wingman_explain1"), shipName);
    end

    applyString(explainLabel, explainText);

    -- 徽章阵营图标
    local campIconImage = findChildByName(self.CT, "bg_2/camp_icon");
    campIconImage:setVisible(false);
end

-- 对飞艇主炮进行排序  按已激活 > 未激活，星级高 > 星级低 排序
function sortWingman(item1, item2)
    if item1.rank ~= item2.rank then
        return item1.rank > item2.rank;
    else
        if item1.skillLevel ~= item2.skillLevel then
            return item1.skillLevel > item2.skillLevel;
        else
            return item1.shipId > item2.shipId;
        end
    end
end

-- 初始化僚机数据
function UISkyCityWingman:initData()
    self.data = {};

    for _, shipId in pairs(self.shipList) do
        local item = {};

        -- 获取数据
        if NewAirShipM.hasOwnShip(shipId) then
            -- 已获得飞艇
            local airshipInfo = NewAirShipM.getUserAirShipInfoWithoutProp(shipId);

            item.shipId = shipId;
            item.rank = airshipInfo.rank;
            item.skillId = NewAirShipM.getAirshipSKill(shipId);
            item.skillLevel = NewAirShipM.getCannonLevel(shipId)
            item.hasOwn = 1;

            -- 1.主炮描述
            local skillId = NewAirShipM.query(shipId, "physic_skill");
            local skillDesc = SkyShipSkillM.getShipSkillDesc(skillId);
            -- 解析一下
            skillDesc = SkyShipSkillM.parseDesc(item.skillId, skillDesc);
            item.skillDesc = skillDesc;
        else
            -- 未获得飞艇
            item.shipId = shipId;
            item.rank = 0;
            item.skillId = NewAirShipM.query(shipId, "physic_skill");
            item.skillLevel = 0;
            item.hasOwn = 0;
        end

        table.insert(self.data, item);
    end

    -- 排序
    table.sort(self.data, sortWingman);
end

-- 初始化僚机格
function UISkyCityWingman:initWingmanGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 8;

    -- 图标宽度
    local iconWidth = 110;

    -- 图片高度
    local iconHeight = 115;

    local topHGap  = 10;
    local leftWGap = 13;

    local bottomHGap = 20;
    -- 收集僚机信息
    local wingmanList = self.data;

    -- 僚机的总个数
    local wingmanCount = #wingmanList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/lictor/LictorItem.csb");
    itemNode:setScale(0.88);

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, wingmanCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerWingmanItemTouchEvent);
end

-- 清空所有的僚机格
function UISkyCityWingman:clearAllGrid()
    -- 格子总数
    local totalGridCount = #self.data;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName(ITEM_NAME .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 注册僚机点击事件
function UISkyCityWingman:registerWingmanItemTouchEvent(node)
    local image = node:getChildByName("bg");
    local grayImage = node:getChildByName("gray_bg");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            if self.data[node.index] == nil then
                return;
            end
            local lastSelected = self.selectIndex;

            self.selectIndex = node.index;

            self:wingmanSelected(lastSelected, node.index);
            -- self:redraw();
        end
    end

    image:addTouchEventListener(onClick);
    grayImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UISkyCityWingman:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityWingman");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册选择按钮点击事件
    local btnSelect = findChildByName(node, "BT/choose_btn");
    local function onSelectClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local data = self.data[self.selectIndex];
            if self:canDispatch(data.shipId) then
                NewAirShipM.dispatch(data.shipId);

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UISkyCityWingman");
            end
        end
    end

    btnSelect:addTouchEventListener(onSelectClick);
    TextStyleM.setTextStyle(btnSelect, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnSelect:setTitleText(getLocStr("btn_text_select"));
end

-- 适配
function UISkyCityWingman:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");

    -- TOP顶部居中并缩放至合适大小
    --AlignM.alignToTopCenter(node, "TOP");
end

-- 僚机选中效果
function UISkyCityWingman:wingmanSelected(lastSelected, nowSelected)
   -- 清除上次选中效果
    local lastSel = self.scrollView:getChildByName(ITEM_NAME .. lastSelected);
    local focusBg = lastSel:getChildByName("focus");
    focusBg:setVisible(false);

    -- 新选中的效果
    local nowSel = self.scrollView:getChildByName(ITEM_NAME .. nowSelected);
    local nowFocusBg = nowSel:getChildByName("focus");
    nowFocusBg:setVisible(true);

    -- 更新说明和按钮
    self:refreshExplain();

    -- 更新选择按钮
    local data = self.data[self.selectIndex];
    local btnSelect = findChildByName(self.node, "BT/choose_btn");

    if not data then
        btnSelect:setBright(false);
        btnSelect:setTouchEnabled(false);
        return;
    end

    if self:canDispatch(data.shipId) then
        btnSelect:setBright(true);
        btnSelect:setTouchEnabled(true);
    else
        btnSelect:setBright(false);
        btnSelect:setTouchEnabled(false);
    end
end

-- 判断能否派遣
function UISkyCityWingman:canDispatch(shipId)
    return NewAirShipM.hasOwnShip(shipId);
end